package com.hk.service.sys.impl;

import java.io.Serializable;
import java.util.List;
import java.util.UUID;

import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import com.hk.commons.CreateUniqueTokensUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.entity.sys.ApiSecret;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.sys.IApiSecret;

@Service
public class ApiSecretImpl extends BaseServiceImpl<ApiSecret> implements
		IApiSecret {

	@Override
	public ApiSecret findById(Long id) {

		return getById(id);
	}

	@Override
	public ApiSecret findByApikey(String apikey) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("apikey", apikey);
		List<ApiSecret> list = super.findByFilter(hqlFilter);

		return list.size() != 0 ? list.get(0) : null;
	}

	@Override
	public int add(ApiSecret model) {
		// 生成api keys
		String uuid = UUID.randomUUID().toString();
		model.setApikey(uuid);
		String apiSecret = RandomStringUtils.randomAlphanumeric(32);
		model.setApiSecret(Md5Crypt.md5Crypt(apiSecret.getBytes()));
		Serializable id = super.save(model);
		
		return (int)id;
	}

	@Override
	public Boolean delete(int id) {
		ApiSecret as = new ApiSecret();
		as.setId(id);
		super.delete(as);
		return true;
	}

}
